﻿using Common;
using ImageSourceModuleCs;
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using T68Control.Procdure;
using VM.Core;
using VM.PlatformSDKCS;

namespace T68Control.S12L_M1
{
    internal class VisionMasterHelper
    {
        private static uint currentProcId;
        public static string VMResult;
        private static bool vmProcHaveExec;
        public static bool vmPorjLoaded;

        public static void LoadVisionProj(string path)
        {
            if (!File.Exists(path))
            {
                throw new FileNotFoundException($"视觉文件[{path}]未找到");
            }
            Task.Run(() =>
            {
                try
                {
                    VisionTool.LoadVMSolution(path);
                }
                catch (Exception ex)
                {
                    Mylog.Error(ex.Message);
                    Global.SetLog?.Invoke(ex.Message);
                }
            });
        }

        public static void ExecVisionFlow(string name)
        {
            // sdk获取图像
            CameraTool.Open();
            var image = CameraTool.GetCurrentImage();
            CameraTool.Close();
            var name2 = name + "Image";
            ImageSourceModuleTool imageSourceModuleTool2 = (ImageSourceModuleTool)VmSolution.Instance[$"{name2}.图像源1"];
            imageSourceModuleTool2.SetImageData(image);
            Application.Current.Dispatcher.BeginInvoke(() =>
            {
                VisionTool.SetProcVisionRet(name + "Image", Global.Control);
            });
            VisionTool.RunProc(name2);
        }

        public static void ExecVisionImageFlow(string path)
        {
            ImageSourceModuleTool imageSourceModuleTool = (ImageSourceModuleTool)VmSolution.Instance[$"显示图片.图像源1"];
            imageSourceModuleTool.SetImagePath(path);
            Application.Current.Dispatcher.BeginInvoke(() =>
            {
                VisionTool.SetProcVisionRet("显示图片", Global.ImageControl);
            });
            VisionTool.RunProc("显示图片");
        }

        public static void ExecVisionFlow(string name, uint id)
        {
            try
            {
                Mylog.Info($"开始执行流程{name}");
                Stopwatch sw = Stopwatch.StartNew();

                vmProcHaveExec = false;

                currentProcId = id;
                // sdk获取图像
                CameraTool.Open();
                var image = CameraTool.GetCurrentImage();
                CameraTool.Close();
                //设置到图像源

                Mylog.Info($"get image finished{sw.ElapsedMilliseconds / 1000.0}s");
                //if (name != "黑屏测试")
                {
                    var name2 = name + "Image";
                    ImageSourceModuleTool imageSourceModuleTool2 = (ImageSourceModuleTool)VmSolution.Instance[$"{name2}.图像源1"];
                    imageSourceModuleTool2.SetImageData(image);
                    Application.Current.Dispatcher.BeginInvoke(() =>
                    {
                        VisionTool.SetProcVisionRet(name + "Image", Global.Control);
                    });
                    VisionTool.RunProc(name2);
                }
                ImageSourceModuleTool imageSourceModuleTool = (ImageSourceModuleTool)VmSolution.Instance[$"{name}.图像源1"];

                imageSourceModuleTool.SetImageData(image);

                Mylog.Info($"1111--{sw.ElapsedMilliseconds / 1000.0}s");
                //Global.TcpServer.ReceiveReady();
                Mylog.Info($"2222--{sw.ElapsedMilliseconds / 1000.0}s");
                VisionTool.RunProc(name);
                bool timeOut = false;
                Mylog.Info($"3333--{sw.ElapsedMilliseconds / 1000.0}s");
                Task.Run(() =>
                {
                    Thread.Sleep(70000);
                    timeOut = true;
                });
                while (!timeOut)
                {
                    if (vmProcHaveExec)
                    {
                        Mylog.Info($"4444--{sw.ElapsedMilliseconds / 1000.0}s");
                        break;
                    }
                    Thread.Sleep(10);
                }
                if (timeOut)
                {
                    // 超时
                    throw new Exception("视觉判定流程执行超时");
                }

                Console.WriteLine($"5555{sw.ElapsedMilliseconds / 1000.0}s");
            }
            catch (Exception ex)
            {
                CameraTool.Close();
                throw ex;
            }
        }

        public static void Init()
        {
            VmSolution.OnWorkStatusEvent += VmSolution_OnWorkStatusEvent;//工作执行状态回调
            VmSolution.OnSolutionLoadEndEvent += VmSolution_OnSolutionLoadEndEvent; //加载方案结束
            VmSolution.OnSolutionLoadBeginEvent += VmSolution_OnSolutionLoadBeginEvent; //加载方案开始
        }

        private static void VmSolution_OnWorkStatusEvent(ImvsSdkDefine.IMVS_MODULE_WORK_STAUS workStatusInfo)
        {
            try
            {
                Mylog.Info($"procid[{workStatusInfo.nProcessID}],status[{workStatusInfo.nWorkStatus}]");
                if (workStatusInfo.nWorkStatus == 0 && workStatusInfo.nProcessID == currentProcId)//为0表示执行完毕，为1表示正在执行；10000表示流程1
                {
                    //通过流程获取结果
                    //VmProcedure vmProcess1 = (VmProcedure)VmSolution.Instance[currentProcName];
                    //String radiusResult = vmProcess1.ModuResult.GetOutputFloat("out").pFloatVal[0].ToString();
                    VMResult = VisionTool.GetGlobalVar("result");
                    vmProcHaveExec = true;
                }
            }
            catch (VmException ex)
            {
                Mylog.Error(ex, ex.Message);
                Global.SetLog?.Invoke(ex.Message);
                //ShowMessage(ex.Message);
            }
        }

        private static void VmSolution_OnSolutionLoadEndEvent(ImvsSdkDefine.IMVS_SOLUTION_LOAD_END_INFO solutionLoadEndInfo)
        {
            try
            {
                //VmSolution.Instance.SilentExecute(1);
                ExecVisionFlow("奇数行测试");
                ExecVisionFlow("偶数行测试");
                ExecVisionFlow("奇数列测试");
                ExecVisionFlow("偶数列测试");
                ExecVisionFlow("全亮工况测试");
                Global.SetLog("视觉文件加载完成");
            }
            catch (VmException vex)
            {
                Mylog.Error(vex, vex.Message);
                Global.SetLog?.Invoke(vex.Message);
            }
            vmPorjLoaded = true;
        }

        private static void VmSolution_OnSolutionLoadBeginEvent(ImvsSdkDefine.IMVS_SOLUTION_LOAD_BEGEIN_INFO solutionLoadBeginInfo)
        {
            vmPorjLoaded = false;
            Global.SetLog("视觉文件开始加载");
        }
    }
}